﻿#include "KeyboardHandler.h"
#include <atlbase.h>

#include <atlapp.h>
#include <atlcrack.h>
#include <atlmisc.h>
#include <shellapi.h>

CAppModule _Module;

class CMainWindow : public CWindowImpl<CMainWindow> {
public:
  DECLARE_WND_CLASS(L"HookF3TrayWindow")

  BEGIN_MSG_MAP_EX(CMainWindow)
  MSG_WM_CREATE(OnCreate)
  MSG_WM_DESTROY(OnDestroy)
  MESSAGE_HANDLER_EX(WM_TRAYICON, OnTrayIcon)
  COMMAND_ID_HANDLER(IDM_EXIT, OnExit)
  END_MSG_MAP()

private:
  enum { IDM_EXIT = 100, WM_TRAYICON = WM_USER + 1 };
  NOTIFYICONDATA m_nid = {sizeof(NOTIFYICONDATA)};

  // 初始化托盘图标
  LRESULT OnCreate(LPCREATESTRUCT /*lpCreateStruct*/) {
    m_nid.hWnd = m_hWnd;
    m_nid.uID = 1;
    m_nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
    m_nid.uCallbackMessage = WM_TRAYICON;
    m_nid.hIcon = AtlLoadIconImage(IDI_APPLICATION, LR_DEFAULTCOLOR, 16, 16);
    wcscpy_s(m_nid.szTip, L"F3快捷助手");
    Shell_NotifyIcon(NIM_ADD, &m_nid);

    // 安装全局钩子
    if (!m_keyboardHandler.InstallHook()) {
      MessageBox(L"无法安装键盘钩子", L"错误", MB_ICONERROR);
      PostQuitMessage(1);
    }
    return 0;
  }

  // 处理托盘图标消息
  LRESULT OnTrayIcon(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam) {
    if (lParam == WM_RBUTTONUP) {
      CMenu menu;
      menu.CreatePopupMenu();
      menu.AppendMenu(MF_STRING, IDM_EXIT, L"退出程序");

      CPoint pt;
      GetCursorPos(&pt);
      SetForegroundWindow(m_hWnd);
      menu.TrackPopupMenu(TPM_RIGHTBUTTON, pt.x, pt.y, m_hWnd);
    }
    return 0;
  }

  // 退出命令处理
  LRESULT OnExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/,
                 BOOL & /*bHandled*/) {
    DestroyWindow();
    return 0;
  }

  // 清理资源
  void OnDestroy() {
    Shell_NotifyIcon(NIM_DELETE, &m_nid);
    PostQuitMessage(0);
  }

private:
  KeyboardHandler m_keyboardHandler;
};
// 修改窗口创建方式
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/,
                   LPSTR /*lpCmdLine*/, int /*nCmdShow*/) {
  _Module.Init(NULL, hInstance);
  CMainWindow wnd;

  // 修改创建参数：添加WS_POPUP样式，移除错误参数
  if (wnd.Create(NULL, CWindow::rcDefault, L"",
                 WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
                 WS_EX_TOOLWINDOW) == NULL) {
    DWORD err = GetLastError();
    TCHAR msg[256] = {0};
    wsprintf(msg, L"创建窗口失败 (错误码: 0x%08X)", err);
    MessageBox(NULL, msg, L"错误", MB_ICONERROR);
    return 1;
  }
  MSG msg;
  while (GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }

  _Module.Term();
  return 0;
}
